import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { FormGroup, FormControl, Validators, FormGroupDirective } from '@angular/forms';

import { ModalController, NavParams } from '@ionic/angular';
import { NavController } from '@ionic/angular';

import { isArray } from 'util';

import { Picker } from 'ng-zorro-antd-mobile';

import { ChooseCityComponent } from '../choose-city/choose-city.component';
import { AppGlobalService } from '../../shared/service/app-global.service';
import { HttpService } from '../../shared/service/http.service';
import { MapBaiduService } from '../../shared/service/map.baiduapi';

import { ShowMapPage } from './show-map/show-map.page';

declare var BMap;

@Component({
  selector: 'app-address',
  templateUrl: './address.page.html',
  styleUrls: ['./address.page.scss'],
  providers: [Picker]
})

export class AddressPage implements OnInit {

  dataList: any;
  thisTable: any;
  allLabel: any = {};
  addressValue: any;
  FormGroup: FormGroup = new FormGroup({});
  data: any;
  doorField: any;
  pageCity: any;
  pageCityCode: any;
  addressItem: any;
  positionInfo: any; // 位置信息临时存储对象 add by andrew.wen
  districtLabel: any;
  constructor(
    private http: HttpService,
    private navParams: NavParams,
    public navController: NavController,
    public modalController: ModalController,
    private appGlobalService: AppGlobalService,
    private mapBaiduService: MapBaiduService
  ) {

  }


  openPicker() {

  }


  ngOnInit() {
    // update by andrew.wen for  需求变动 城市字段增加默认值，默认是当前定位城市，并且可以修改
    // this.positionInfo = JSON.parse(this.mapBaiduService.getStore('currentCityPosition'))
    //   ? JSON.parse(this.mapBaiduService.getStore('currentCityPosition'))
    //   : { 'name': '深圳', 'code': 4403 };
    this.positionInfo = JSON.parse(localStorage.getItem('position'));
    console.log(this.positionInfo, 'this.positionInfo')
    this.addressValue = {};
    this.data = JSON.parse(this.navParams.data.value);
    // tslint:disable-next-line:prefer-for-of
    for (let i = 0; i < this.data.item.length; i++) {
      const value = this.data.item[i];
      if (value.type === 'toggle') {
        if (value.writable) {
          const rangeLen = value.itemObj.itemList.length;
          for (let k = 0; k < rangeLen; k++) {
            const itemList = value.itemObj.itemList[k];
            itemList.value = itemList.value ? (itemList.value.substr(0, 2).indexOf('#') > -1 ? '' : itemList.value) : '';
            this.FormGroup.addControl(value.itemObj.itemList[k].field, new FormControl(itemList.value, this.validators(itemList)));
            this.allLabel[value.field] = value.label;
          }
        } else {
          this.FormGroup.addControl(value.field, new FormControl(value.value, this.validators(value)))
        }
      } else if (value.type === 'dropDownBox') {
        value.itemList = [];
        this.thisTable = value;
        this.getDropDownData(value, this.pageCityCode);
        // this.getPickerLabel(value);
        this.FormGroup.addControl(value.field, new FormControl(value.value, this.validators(value)));
        this.allLabel[value.field] = value.label;
      } else if (value.type === 'text' && value.writable) {
        this.FormGroup.addControl(value.field, new FormControl(value.value, this.validators(value)));
        this.FormGroup.addControl(value.itemObj.field, new FormControl(value.itemObj.value, this.validators(value.itemObj)));
        this.allLabel[value.field] = value.label;
        this.allLabel[value.itemObj.field] = value.itemObj.label;
      } else if (value.type === 'dropDownSelect' && value.writable) {
        this.FormGroup.addControl(value.field, new FormControl(value.value, this.validators(value)));
        this.FormGroup.addControl(value.itemObj.field, new FormControl(value.itemObj.value, this.validators(value.itemObj)));
        value.dropDownList.dropDownItem.push({ code: '-1', name: "自定义" });
        this.allLabel[value.field] = value.label;
        this.allLabel[value.itemObj.field] = value.itemObj.label;
      } else if (value.type === 'address') {
        value.cityCode = this.positionInfo.code;
        value.cityName = this.positionInfo.name;
        this.addressItem = value;
        // this.addressValue = { value: value.value, latitude: value.latitude, longitude: value.longitude, cityName: value.cityName };
        this.addressValue = { value: value.value, location: value.locationValue, cityName: value.cityName };
        this.FormGroup.addControl(value.location, new FormControl(value.locationValue));
        this.FormGroup.addControl(value.field, new FormControl(value.value, this.validators(value)));
        this.allLabel[value.field] = value.label;
        value.detail = value.value;
      } else if (value.type === "text" && !value.writable) {
        this.doorField = value.field;
        this.FormGroup.addControl(value.field, new FormControl(value.value, this.validators(value)));
        this.allLabel[value.field] = value.label;
      } else if (value.type === 'gotoPage') {
        value.cityName = value.translateName || this.positionInfo.name;
        value.value = value.value || this.positionInfo.code;
        this.pageCityCode = value.value;
        this.pageCity = value.cityName;
        this.FormGroup.addControl(value.field, new FormControl(value.value, this.validators(value)));
        this.allLabel[value.field] = value.label;
      } else {
        this.FormGroup.addControl(value.field, new FormControl(value.value, this.validators(value)));
        this.allLabel[value.field] = value.label;
      }
    }
  }

  onOk2(result, item) {
    if (result.length && isArray(result)) {
      if (result.length === 1) {
        item.value = result[0].code;
        item.checkLabel = `${result[0].label}`;
      } else {
        item.value = result[1].code;
        item.checkLabel = `${result[0].label} ${result[1].label}`;
      }
      this.districtLabel = item.checkLabel;
      this.getPointByCityName(this.positionInfo.name, this.districtLabel);
    }
  }

  getDropDownData(item, city?) {
    console.log(item, 'addditem');
    const table = {
      table: item.table
    };
    if (city) { table.table.condition[0].valueStr = city; }
    const params = {
      content: table,
      // tslint:disable-next-line:no-string-literal
      id: this.data['id'],
      sessionId: localStorage.getItem('sessionId')
    };
    // 请求获取新数据
    this.http.post('application/submit', params, res => {
      // 请求数据成功
      if (res.data.data) {
        item.itemList = res.data.data;
        this.getPickerLabel(item);
      } else {
        // 请求数据失败 此时不应该在报错
        // tslint:disable-next-line:no-string-literal
        // this.appGlobalService.showToast(res['message'], 2000, 'middle');
      }
    });
  }

  getPickerLabel(item) {
    if (item.value) {
      item.itemList.forEach(element => {
        if (!element.children || !element.children.length) {
          if (element.code === item.value) {
            item.checkLabel = element.label;
          }
        } else {
          const prev = element;
          element.children.forEach(ele => {
            if (ele.code === item.value) {
              item.checkLabel = element.label + ' ' + ele.label;
            }
          });
        }
        if (!item.checkLabel) {
          item.checkLabel = item.hint;
        }
      });
    } else {
      item.checkLabel = item.hint;
    }
    this.districtLabel = item.checkLabel;
  }

  async showCityModel(item) {
    if (item.isDisabled && item.disabledTips) {
      this.showDisabledTips(item);
      return;
    }
    const that = this;
    const modal = await this.modalController.create({
      component: ChooseCityComponent,
      componentProps: { value: item.target, modalTitle: '选择城市', noStorage: true }
    });
    modal.onDidDismiss().then((data) => {
      const value = data.data;
      if (value !== undefined && value.n !== undefined) {
        that.pageCity = value.n;
        that.pageCityCode = value.i;
        item.cityName = value.n;
        item.translateName = value.n;
        item.value = value.i;
        that.positionInfo.code = value.i;
        that.positionInfo.name = value.n;
        that.FormGroup.patchValue({ [item.field]: value.i });
        that.getDropDownData(that.thisTable, value.i);
        that.addressItem.value = "";
        that.thisTable.checkLabel = "";
        if (that.doorField) { that.FormGroup.patchValue({ [that.doorField]: '' }); }
        that.getPointByCityName(item.cityName);
      }
    });
    return await modal.present();
  }

  // update by andrew.wen for 获取经纬度
  getPointByCityName(cityName, districtName?) {
    const that = this;
    const myGeo = new BMap.Geocoder();
    myGeo.getPoint((districtName !== undefined ? cityName + districtName : cityName), (point) => {
      if (point) {
        that.positionInfo.center.lng = point.lng;
        that.positionInfo.center.lat = point.lat;
      }
    }, cityName);
  }


  async showSelectAddressModel(item) {
    // console.log(item, 'igiggigigi');
    if (document.getElementById('showSelectAddressModelId').getAttribute('showAddressModal')) {
      return;
    } else {
      document.getElementById('showSelectAddressModelId').setAttribute('showAddressModal', 'true');
    }
    const that = this;
    if (that.pageCity !== undefined && that.pageCityCode !== undefined) {
      item.cityName = that.pageCity;
      item.cityCode = that.pageCityCode;
      // item.longitude = that.positionInfo.center.lng;
      // item.latitude = that.positionInfo.center.lat;
      item.locationValue = that.positionInfo.center.lat.toString() + "," + that.positionInfo.center.lng.toString();
    }
    const modal = await this.modalController.create({
      showBackdrop: true,
      component: ShowMapPage,
      componentProps: { value: item }
    });
    await modal.present();
    const { data } = await modal.onDidDismiss();
    if (data !== undefined) {
      Object.assign(this.addressValue, data);
      this.FormGroup.patchValue({ [item.field]: data.value, [item.location]: data.location });
      item.value = data.value;
      item.locationValue = data.locationValue;
      // item.longitude = data.longitude;
      item.cityName = data.cityName;
      item.cityCode = data.cityCode;
    }
  }


  goBack() {
    if (this.FormGroup.invalid) {
      this.getErrors(this.FormGroup);
      return;
    }
    this.addressValue.districtLabel = this.districtLabel;
    this.addressValue.door = this.FormGroup.value[this.doorField];
    this.addressValue.pageCityName = this.pageCity;
    this.modalController.dismiss({ form: this.FormGroup, detail: this.addressValue });
  }

  validators(item) {
    const validators = [];
    if (item.isRequire) {
      validators.push(Validators.required);
    }
    if (item.rule) {
      validators.push(Validators.pattern(item.rule));
    }
    if (item.maxLength) {
      validators.push(Validators.maxLength(item.maxLength));
    }
    if (item.minLength) {
      validators.push(Validators.minLength(item.minLength));
    }
    return validators;
  }

  getErrors(form) {
    const errs = [];
    // tslint:disable-next-line:no-string-literal
    for (const name in form['controls']) {
      // tslint:disable-next-line:no-string-literal
      if (form['controls'][name].errors) {
        // tslint:disable-next-line:no-string-literal
        errs.push({ key: [name], err: form['controls'][name].errors });
      }
    }
    if (errs.length) {
      const name = errs[0];
      if (name.err.required !== undefined) {
        this.appGlobalService.showToast(`请输入${this.allLabel[name.key]}`, 3000, 'top');
      } else if (name.err.pattern !== undefined) {
        this.appGlobalService.showToast(`${this.allLabel[name.key]}数据输入不正确`, 3000, 'top');
      }
    }
    console.log(errs, 'errorsssssssssss');
  }

  cancel() {
    this.modalController.dismiss();
  }
  inputClick(item) {
    this.showDisabledTips(item);
  }
  showDisabledTips(item) {
    if (item.isDisabled && item.disabledTips) {
      this.appGlobalService.showToast(item.disabledTips, 1500, 'middle');
    }
  }
}
